package com.shirley.netty.handlerorder.inbound;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

public class InBoundWritingHandler extends ChannelInboundHandlerAdapter {
    static AtomicInteger count = new AtomicInteger(0);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Into InBoundWritingHandler.channelRead");
        String data = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
        System.out.println("InBoundWritingHandler.channelRead receive: " + data);
        ctx.writeAndFlush(Unpooled.copiedBuffer("TCP Server had got msg, index = " + count.incrementAndGet(),
                CharsetUtil.UTF_8));

        // If do not call fireChannelRead, the next ChannelHandler will not exec.
        ctx.fireChannelRead(msg);
        System.out.println("Exit InBoundWritingHandler channelRead");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("InBoundWritingHandler readComplete.");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("InBoundWritingHandler exceptionCaught.");
    }

}
